import httpUtil from "./httpUtil"
import messageUtil from "@/utils/messageUtil.js"
// #ifdef H5
import download from "downloadjs"
// #endif


const downloadOne = (fileUrl) => {
	if (process.env.NODE_ENV === 'development') {
		fileUrl = httpUtil.devHost + fileUrl
	}

	// #ifdef H5
	h5Download(fileUrl)
	// #endif
	// #ifndef H5
	miniDownload(fileUrl)
	// #endif
}

// #ifdef H5
const h5Download = (fileUrl) => {
	try {
		download(fileUrl);
		messageUtil.showSuccess('保存成功')
	} catch (err) {
		messageUtil.showSuccess('保存失败')
	}

}
// #endif

// #ifndef H5
const miniDownload = (fileUrl) => {
	uni.downloadFile({
		url: fileUrl, //仅为示例，并非真实的资源
		success: (res) => {
			if (res.statusCode === 200) {
				uni.saveFile({
					tempFilePath: res.tempFilePath,
					success: function(res) {
						// var savedFilePath = res.savedFilePath;
						console.log('saveFile success', JSON.stringify(res))
						messageUtil.showSuccess('保存成功')
					},
					fail: function(err) {
						console.log('saveFile fail', JSON.stringify(err))
					}
				});
			} else {
				messageUtil.showFail('下载文件失败')
			}
		},
		fail: (err) => {
			console.log('downloadFile', JSON.stringify(err))
			messageUtil.showFail('下载文件失败')
		}
	});
}
// #endif


export default {
	downloadOne,
}
